package com.eims.sls_app.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.RequestParams;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.Information;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.EmailHandler;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

public class Information_Detail extends MyBaseActivity implements OnClickListener {
	private String auth;
	private String info;
	private WebView tx_show;
	private TextView informationDetail_Datetime, informationDetail_recordCount,
			informationDetail_title, informationDetail_Current,
			informationDetail_Sum;
	private Button informationDetail_Pervious, informationDetail_Next;
	private ImageButton information_detail_share, btn_back;
	private Context context;
	private MyHandler handler;
	private List<Information> informations = new ArrayList<Information>();
	private Information informations_show = new Information();

	private int newType = 2;
	private long currentNewId;
	private long[] ids;
	private int newIndex = 1;
	private UMSocialService mController;
	private static final String SHARE_PAGE = "com.umeng.share";
	private String TAG = "Information_Detail";
	private MySingleton mySingleton;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_informationdetail);
		App.activityS.add(this);
		findView();
		initBundle();
		setListener();
		getInformation();
		getHttpRes(false);
	}

	private void findView() {
		handler = new MyHandler();
		information_detail_share = (ImageButton) findViewById(R.id.information_detail_share);
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		tx_show = (WebView) this.findViewById(R.id.tx_show);
		informationDetail_Current = (TextView) this
				.findViewById(R.id.informationDetail_Current);
		informationDetail_Sum = (TextView) this
				.findViewById(R.id.informationDetail_Sum);
		informationDetail_title = (TextView) this
				.findViewById(R.id.information_detail_title);
		informationDetail_Datetime = (TextView) this
				.findViewById(R.id.informationDetail_Datetime);
		informationDetail_recordCount = (TextView) this
				.findViewById(R.id.informationDetail_recordCount);
		informationDetail_Pervious = (Button) this
				.findViewById(R.id.informationDetail_Pervious);
		informationDetail_Next = (Button) this
				.findViewById(R.id.informationDetail_Next);
		context = getApplicationContext();
		mySingleton = MySingleton.getInstance(context);
	}

	private void setListener() {
		informationDetail_Pervious.setOnClickListener(this);
		informationDetail_Next.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		information_detail_share.setOnClickListener(this);
	}

	/**
	 * 获取当前资讯的分享url
	 */
	private void getHttpRes(boolean force) {
		if (NetWork.isConnect(context)) {
			String opt = "67";
			String info = "{\"infoType\":\"" + newType + "\",\"urlId\":\""
					+ currentNewId + "\"}";
			JsonObjectRequest request = new JsonObjectRequest(App.path,
					RequestParams.convertParams(context, opt, info),
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Log.i(TAG, "JSONObject response==>" + response);

							// 04-14 09:25:26.108:
							// I/Information_Detail(1212):JSONObject
							// response==>{"error":"0","msg":"",
							// "url":"http:\/\/sls53.test.shovesoft.net\/Home\/Web\/ShowNewSpecial.aspx?ID=3"}
							url = (String) response.opt("url");
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							RequestParams.convertError(context, error, true);
						}
					});
			request.setTag(TAG);
			request.setCacheTime(JsonRequest.CONFIG_CACHE_SHORT);
			if (force) {// 删除缓存
				mySingleton.dropCache(request.getCacheKey());
			}
			mySingleton.addToRequestQueue(request);

		} else {
			MyToast.getToast(context, "网络连接异常，请检查网络").show();
		}
	}

	private void initBundle() {
		Intent intent = getIntent();
		Bundle bundle = intent.getBundleExtra("informationList");
		if (bundle != null) {
			newType = bundle.getInt("newType");
			currentNewId = bundle.getLong("currentNewId");
			ids = bundle.getLongArray("ids");
			newIndex = bundle.getInt("newIndex");
		}
	}

	private void showContent() {
		informationDetail_Current.setText((newIndex + 1) + "");
		informationDetail_Sum.setText(ids.length + "");
		informationDetail_title.setText(informations_show.getTitle());
		informationDetail_Datetime.setText("发表："
				+ informations_show.getDateTime());
		informationDetail_recordCount.setText("来源：联盈助手网");
		if (informations_show.getContent() != null) {
			System.out.println("infomation_contnet===="
					+ informations_show.getContent() + "=====止");
			String Url = informations_show.getContent();
			WebSettings websetting = tx_show.getSettings();
			websetting.setJavaScriptEnabled(true);
			websetting.setSavePassword(false);
			websetting.setSupportZoom(false);
			websetting.setSaveFormData(false);
			tx_show.setWebChromeClient(new WebChromeClient());
			tx_show.loadUrl(Url);
			// 如果页面中链接，如果希望点击链接继续在当前browser中响应，
			// 而不是新开Android的系统browser中响应该链接，必须覆盖webview的WebViewClient对象
			tx_show.setWebViewClient(new WebViewClient() {
				public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
					view.loadUrl(url);
					return true;
				}
			});
			// tx_show.loadDataWithBaseURL(null,"<html><body>" +
			// informations_show.getContent()
			// + "</body></html>", "text/html", "utf-8",null);
		} else
			tx_show.loadData("咨询已经修改", "text/html", "UTF-8");
	}

	private void getInformation() {
		Boolean isrequest = true;
		for (Information information : informations) {
			if (information.getId() == currentNewId) {
				isrequest = false;
				informations_show = information;
				break;
			}
		}
		if (isrequest) {
			if (NetWork.isConnect(getApplicationContext())) {
				String mImei = RspBodyBaseBean.getIMEI(context);
				String mTime = RspBodyBaseBean.getTime();
				String uid = "-1";
				String password = "";
				if (null != App.user) {
					uid = App.user.getUid();
					password = App.user.getUserPass();
				}
				info = RspBodyBaseBean.getInformationDetail(newType,
						currentNewId);
				String mCrc = RspBodyBaseBean.getCrc(mTime, mImei,
						App.key, info, uid);
				// String mCrc = RspBodyBaseBean.getCrc(mTime, mImei,
				// MD5.md5(password + App.MD5_key), info, uid);
				auth = RspBodyBaseBean.getAuth(mCrc, mTime, mImei, uid);
				MyAsynTask mMyAsynTask = new MyAsynTask();
				mMyAsynTask.execute();
			} else {
				MyToast.getToast(getApplicationContext(), "网络连接异常，请检查网络")
						.show();
			}
		} else {
			showContent();
		}

	}

	/**
	 * 上一条或者下一条
	 */
	private void previousOrNext() {
		getInformation();
		getHttpRes(false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.information_detail_share:
			initUMShare();
			mController.openShare(this, false);
			break;
		case R.id.informationDetail_Pervious:
			if (ids == null) {
				MyToast.getToast(getApplicationContext(), "数据异常").show();
				return;
			}
			if (ids.length <= 0) {
				MyToast.getToast(getApplicationContext(), "数据异常").show();
				return;
			} else if (ids.length == 1) {
				return;
			} else {
				if (newIndex == 0) {
					return;
				} else {
					newIndex = newIndex - 1;
				}
				currentNewId = ids[newIndex];
			}
			previousOrNext();
			break;

		case R.id.informationDetail_Next:
			if (ids == null) {
				MyToast.getToast(getApplicationContext(), "数据异常").show();
				return;
			}
			if (ids.length <= 0) {
				MyToast.getToast(getApplicationContext(), "数据异常").show();
				return;
			} else if (ids.length == 1) {
				return;
			} else {
				if (newIndex == ids.length - 1) {
					return;
				} else {
					newIndex = newIndex + 1;
				}
				currentNewId = ids[newIndex];
			}
			previousOrNext();
			break;

		default:
			break;
		}
	}

	private String addInformation(JSONObject items) {
		if (informations_show == null) {
			informations_show = new Information();
		}
		currentNewId = items.optLong("informationId");
		informations_show.setId(currentNewId);
		informations_show.setReadCount(items.optInt("readCount"));
		informations_show.setParentTypeId(newType);
		informations_show.setDateTime(items.optString("dateTime"));
		informations_show.setUrl(items.optString("URL"));
		informations_show.setTitle(items.optString("title"));
		try {
			informations_show.setContent(URLDecoder.decode(
					items.optString("content"), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			VolleyLog.e("UnsupportedEncodingException=>%s", e.toString());
			return "2";
		}
		informations.add(informations_show);
		return "1";
	}

	/**
	 * 异步任务 用来后台获取数据
	 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {
		/**
		 * 在后台执行的程序
		 */
		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = BaseHelper.showProgress(Information_Detail.this, null,
					"加载中..", false, true);
			dialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			String mOpt = "45";
			String values[] = { mOpt, auth, info };
			String result = HttpUtils.doPost(App.names, values,
					App.path);
			System.out.println("+++++++++opt====" + mOpt + "++++info===="
					+ info);
			System.out.println("++++=====result++++" + result);
			VolleyLog.e("info=>%s,result=>%s", info, result);

			if ("-500".equals(result)) {
				return result;
			}
			JSONObject item = null;
			try {
				item = new JSONObject(result);
			} catch (Exception ex) {
				VolleyLog.e("Exception=>%s", ex.toString());
			}
			if (item != null) {
				if ("0".equals(item.optString("error"))) {
					int i = -1;
					for (int j = 0; j < informations.size(); j++) {
						if (informations.get(j).getId() == currentNewId) {
							i = j;
						}
					}
					if (i != -1) {
						informations.remove(i);
					}
					return addInformation(item);
				} else {
					VolleyLog.e("msg=>%s", item.optString("msg"));
				}
			}
			return "2";
		}

		@Override
		protected void onPostExecute(String result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			handler.sendEmptyMessage(1);
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				showContent();
				break;
			case 2:
				MyToast.getToast(getApplicationContext(), "暂无内容").show();
				break;
			case -500:
				MyToast.getToast(Information_Detail.this, "连接超时").show();
				break;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	private void initUMShare() {
		if (url != null) {
			mController = UMServiceFactory.getUMSocialService(SHARE_PAGE);
			QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this,
					"100424468", "c7394704798a158208a74ab60104f0ba");
			qZoneSsoHandler.setTargetUrl(url);
			qZoneSsoHandler.addToSocialSDK();
			SmsHandler sms = new SmsHandler();
			sms.addToSocialSDK();
			EmailHandler email = new EmailHandler();
			email.addToSocialSDK();
			// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
			String appID = "wx50d3df0a66e8ffc7";
			String appSecret = "a67e72f25a2683460b1e87b05515f28b";
			// 添加微信平台
			UMWXHandler wxHandler = new UMWXHandler(this, appID, appSecret);
			wxHandler.setTargetUrl(url);
			wxHandler.setTitle(informations_show.getTitle());
			wxHandler.addToSocialSDK();
			// 支持微信朋友圈
			UMWXHandler wxCircleHandler = new UMWXHandler(this, appID,
					appSecret);
			wxCircleHandler.setToCircle(true);
			wxCircleHandler.setTargetUrl(url);
			wxCircleHandler.setTitle(informations_show.getTitle());
			wxCircleHandler.addToSocialSDK();
			// 设置显示的平台和顺序
			mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN,
					SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE,
					SHARE_MEDIA.SINA, SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN,
					SHARE_MEDIA.SMS, SHARE_MEDIA.EMAIL);
			// 设置平台顺序
			mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN,
					SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE,
					SHARE_MEDIA.SINA, SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN,
					SHARE_MEDIA.SMS, SHARE_MEDIA.EMAIL);

			mController.setShareContent(informations_show.getTitle() + url);
			// 人人网
			mController.setAppWebSite(SHARE_MEDIA.RENREN, url);
			mController
					.setShareMedia(new UMImage(this, R.drawable.icon_new));
		}
	}
}
